package com.basic.java.threads.sync.safe;

/**
 * 类
 * 创建时间：2022/4/19 22:22
 *
 * @author gejin
 */
public class SafeBank {
    public static void main(String[] args) {
        Account account = new Account(1000, "123456");

        new Drawing(account, 200, "you").start();
        new Drawing(account, 900, "girlFriend").start();
    }
}

// 模拟银行账户
class Account {
    private int money; // 卡里的钱
    private String cardName; // 卡号

    public Account(int money, String cardName) {
        this.money = money;
        this.cardName = cardName;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public String getCardName() {
        return cardName;
    }

    public void setCardName(String cardName) {
        this.cardName = cardName;
    }
}

// 模拟取钱
class Drawing extends Thread {
    // 账户
    Account account;
    // 需要取的钱
    private int drawMoney;
    // 现在手里有多少钱
    private int nowMoney;

    public Drawing(Account account, int drawMoney, String name) {
        super(name);
        this.account = account;
        this.drawMoney = drawMoney;
    }

    @Override
    public void run() {
        synchronized (account) {
            // 判断有没有钱
            if (account.getMoney() - drawMoney < 0) {
                System.out.println(Thread.currentThread().getName() + "钱不够了， 取不了");
                return;
            }
            // 取钱
            try {
                drawingMoney();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void drawingMoney() throws InterruptedException {
        Thread.sleep(1000);
        // 卡里的余额 = 账户的钱 - 取出来的钱
        account.setMoney(account.getMoney() - drawMoney);
        // 现在手里的钱 = 现在的钱 + 取出来的钱
        nowMoney = nowMoney + drawMoney;

        System.out.println(account.getCardName() + "余额为：" + account.getMoney());
        System.out.println(this.getName() + "手里的钱：" + nowMoney);
    }
}